import Cookies from 'js-cookie'
import { login } from '@/api'
import routes from '@/router/routes'
import { routes_filter } from '@/utils'

export default {
    namespaced: true,
    state: {
        user_info: null
    },
    getters: {
        allow_routes(state) {
            if (state.user_info) {
                return routes_filter(state.user_info.role, routes)
            }
            return []
        }
    },
    mutations: {
        set_user_info(state, user_info) {
            state.user_info = user_info
        }
    },
    actions: {
        async user_login({ commit }, params) {
            const user = await login(params)
            // user 是个对象
            // 将登录信息保存到 cookie 中
            Cookies.set('user_info', JSON.stringify(user))
            commit('set_user_info', user)
            return true
        },
        user_logout({ commit }) {
            Cookies.remove('user_info')
            commit('set_user_info', null)
        },
        user_auth({ commit }) {
            // 从 cookie 中获取登录信息
            const user_info = Cookies.get('user_info')
            if (user_info) {
                commit('set_user_info', JSON.parse(user_info))
            }
        }
    }
}